import {
	defineStore
} from 'pinia';

export const useCartStore = defineStore('cart', {
	state: () => {
		return {
			cartlist: [],
			// {
			// 	id: 1,
			// 	Titles: '酒白芍配方颗粒酒白芍配方颗粒',
			// 	PicFiles: "http://baihang.com.cn/Upload/image/2021090904LMFFG9.jpg",
			// 	Price: 12.12,
			// 	spcc: "每袋装0.83g",
			// 	Minnum: 200,
			// 	Step: 20,
			// 	count: 220,
			//  checked:true
			// }
		};
	},
	actions: {
		initCart() {
			uni.getStorage({
				key: 'storage_cart',
				success: (res) => {
					this.cartlist = res.data
				}
			});
		},
		//数量改变
		changeCartItem(payload) {
			const {
				good,
				num
			} = payload;
			//判断是否有记录 没有则新增一条记录
			let _ind = this.cartlist.findIndex(item => {
				return item.id == good.id;
			})
			//不存在则新增
			if (_ind < 0) {
				good.count = num;
				good.checked = true;
				this.cartlist.unshift(good);
			} else {
				this.cartlist[_ind].count += num;
				//此时删除该记录   此时为最小数量
				if (this.cartlist[_ind].count < this.cartlist[_ind].Minnum) {
					// this.cartlist.splice(_ind, 1);
					this.cartlist[_ind].count = this.cartlist[_ind].Minnum;
					uni.showToast({
						icon: 'none',
						title: '不得少于起购数',
						duration: 1000
					});
				}
			}
			uni.setStorage({
				key: 'storage_cart',
				data: this.cartlist
			});
		},
		// 全选
		allChecked(toggle) {
			this.cartlist.forEach(item => {
				item.checked = toggle;
			})
			uni.setStorage({
				key: 'storage_cart',
				data: this.cartlist
			});
		},
		//单选
		itemChecked(goodid) {
			this.cartlist.forEach(item => {
				if (item.id == goodid) {
					item.checked = !item.checked;
				}
			})
			uni.setStorage({
				key: 'storage_cart',
				data: this.cartlist
			});
		},
		//删除选中
		deleteCart() {
			this.cartlist = this.cartlist.filter(item => {
				return !item.checked
			})
			uni.setStorage({
				key: 'storage_cart',
				data: this.cartlist
			});
		}
	},
	getters: {
		//所有选中的商品
		cartCheckedList: (state) => {
			return state.cartlist.filter(item => {
				return item.checked
			})
		},
		//所选商品总数
		cartTotalAllCount: (state) => {
			return state.cartlist.reduce((total, item) => {
				return total + item.count
			}, 0)
		},
		//选中的商品数量
		cartTotalCount: (state) => {
			if (state.cartlist.length == 0) {
				return 0
			}
			return state.cartlist.reduce((total, item) => {
				if (item.checked) return total + item.count;
				return total + 0;
			}, 0);
		},
		//选中的商品总价
		cartTotalPrice: (state) => {
			if (state.cartlist.length == 0) {
				return 0
			}
			return state.cartlist.reduce((total, item) => {
				if (item.checked) return total + item.count * item.Price;
				return total + 0;
			}, 0).toFixed(2);
		},
		//全选的状态
		isAllchecked: (state) => {
			return state.cartlist.every(item => {
				return item.checked == true
			})
		}
	}
});